package org.jeecg.modules.foc;


import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.time.DateFormatUtils;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.util.Md5Util;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.modules.c.entity.*;
import org.jeecg.modules.c.service.*;
import org.jeecg.modules.common.FocRequest;
import org.jeecg.modules.common.FocRespone;
import org.jeecg.modules.foc.entity.*;
import org.jeecg.modules.foc.service.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.*;


@Slf4j
@Api(tags = "foc操作")
@RestController
@RequestMapping("/foc/auto")
public class FocController {

    @Value("${ems.url}")
    public String emsUrl;

    @Autowired
    RedisUtil redisUtil;


    @Autowired
    private IFocConfigService focConfigService;
    @Autowired
    @Lazy
    private IFocSpaceService focSpaceService;

    @Autowired
    private IFocPointService focPointService;
    @Autowired
    @Lazy
    private IFocDeviceService focDeviceService;
    @Autowired
    private IMSignalService mSignalService;
    @Autowired
    private IMDeviceService mDeviceService;
    @Autowired
    private IMSiteService mSiteService;
    @Autowired
    private IMRoomService mRoomService;
    @Autowired
    private IMAreaService mAreaService;


    /**
     * 登录foc
     */
    @AutoLog(value = "foc操作-login")
    @ApiOperation(value = "foc操作-login", notes = "foc操作-login")
    @RequestMapping(value = "/login")
    //@PostConstruct
    public FocRespone login() {
        //组装请求体
        FocRequest focRequest = new FocRequest();
        LonginDTO longinDTO = new LonginDTO();
        String pwd = Md5Util.md5Encode("CInterface", "utf-8");
        longinDTO.setUsername("CInterface");
        longinDTO.setPassword(pwd);
        longinDTO.setIp("202.151.2.1");
        longinDTO.setLogin_time(System.currentTimeMillis());
        focRequest.setData(longinDTO);
        String post = "";
        log.debug("登录请求路径以及参数：" + emsUrl + "/north/login" + " 请求参数：" + JSONObject.toJSONString(focRequest));
        try {
            post = HttpUtil.post(emsUrl + "/north/login", JSONObject.toJSONString(focRequest));
        } catch (Exception e) {

            log.error("登录失败：{}", e.getMessage());
        }

        log.debug("登录返回信息：{}", post);
        JSONObject result = JSONObject.parseObject(post);
        String token = result.getJSONObject("data").getString("token");
        redisUtil.set("token", token);
        return FocRespone.ok();
    }

    /**
     * 登录foc
     */
    @AutoLog(value = "foc操作-手动刷新-下划线")
    @ApiOperation(value = "foc操作-手动刷新-下划线", notes = "foc操作-手动刷新-下划线")
    @RequestMapping(value = "/spaceConvertAll")
    @PostConstruct
    @Transactional(rollbackFor = Exception.class)
    public FocRespone spaceConvertAll() {

        //省市区转换
        spaceConvertSide();
        //局站转换
        spaceConvert();
        return FocRespone.ok();
    }

    /**
     * 登录foc
     */
    @AutoLog(value = "foc操作-手动刷新-下划线")
    @ApiOperation(value = "foc操作-手动刷新-下划线", notes = "foc操作-手动刷新-下划线")
    @RequestMapping(value = "/spaceConvertSide")
    //   @PostConstruct
    @Transactional(rollbackFor = Exception.class)
    public FocRespone spaceConvertSide() {
        log.info("开始执行spaceConvertSide方法 - 处理省份和城市区县转换");

        try {
            //处理省份
            log.info("开始处理省份数据 - 设置中心类型为1");
            LambdaUpdateWrapper<FocSpace> spaceLambdaUpdateWrapper = new LambdaUpdateWrapper<FocSpace>();
            spaceLambdaUpdateWrapper.eq(FocSpace::getSpaceType, "中心");
            spaceLambdaUpdateWrapper.set(FocSpace::getType, 1);
            spaceLambdaUpdateWrapper.set(FocSpace::getDelFlag, 0);
            boolean provinceUpdateResult = focSpaceService.update(spaceLambdaUpdateWrapper);
            log.info("省份数据更新结果: {}", provinceUpdateResult);

            //处理城市和区县
            log.info("开始查询楼宇类型数据");
            LambdaQueryWrapper<FocSpace> spaceLambdaQueryWrapper = new QueryWrapper<FocSpace>().lambda();
            spaceLambdaQueryWrapper.eq(FocSpace::getSpaceType, "楼宇");
            spaceLambdaQueryWrapper.eq(FocSpace::getDelFlag, 0);
            List<FocSpace> list = focSpaceService.list(spaceLambdaQueryWrapper);
            log.info("查询到楼宇数据数量: {}", list != null ? list.size() : 0);

            //如果不为空则进行遍历
            if (CollectionUtil.isEmpty(list)) {
                log.warn("楼宇数据为空，直接返回");
                return FocRespone.ok();
            }

            //默认只有一个中心
            int processedCount = 0;
            int errorCount = 0;

            for (FocSpace focSpace : list) {
                try {
                    log.info("开始处理楼宇: guid={}, name={}", focSpace.getGuid(), focSpace.getName());

                    //对名称进行分割
                    String[] split = focSpace.getName().split("#");
                    if (split == null) {
                        log.warn("楼宇名称分割结果为空: {}", focSpace.getName());
                        errorCount++;
                        continue;
                    }
                    if (split.length != 2) {
                        log.warn("楼宇名称分割长度不正确，期望2个部分，实际{}个部分: {}", split.length, focSpace.getName());
                        errorCount++;
                        continue;
                    }
                    if (split[1] == null) {
                        log.warn("楼宇名称分割后第二部分为空: {}", focSpace.getName());
                        errorCount++;
                        continue;
                    }

                    log.info("楼宇名称分割成功: 城市={}, 区县={}", split[0], split[1]);

                    //构建市区
                    //创建新城市
                    FocSpace citySpace = new FocSpace();
                    //查询老节点配置是否存在
                    String cityGuid = focSpace.getParentGuid() + "_" + split[0];
                    log.info("查询城市节点，guid: {}", cityGuid);
                    FocSpace oldCitySpace = focSpaceService.getOne(new QueryWrapper<FocSpace>().eq("guid", cityGuid).eq("type", 2));
                    if (oldCitySpace != null) {
                        log.info("找到已存在的城市节点: {}", oldCitySpace.getGuid());
                        citySpace = oldCitySpace;
                        citySpace.setId(null);
                    }

                    citySpace.setType(2);
                    citySpace.setUpdateTime(new Date());
                    citySpace.setGuid(cityGuid);
                    citySpace.setName(split[0]);
                    citySpace.setParentGuid(focSpace.getParentGuid());
                    citySpace.setSpaceType("城市");
                    citySpace.setDelFlag(0);

                    boolean citySaveResult = focSpaceService.saveOrUpdate(citySpace);
                    log.info("城市节点保存/更新结果: {}, guid: {}", citySaveResult, citySpace.getGuid());

                    //根据城市构建区县
                    FocSpace area = new FocSpace();
                    //查询老节点配置是否存在
                    String areaGuid = focSpace.getGuid() + "N";
                    log.info("查询区县节点，guid: {}", areaGuid);
                    FocSpace oldAreaSpace = focSpaceService.getOne(new QueryWrapper<FocSpace>().eq("guid", focSpace.getParentGuid() + "_" + split[0] + "_" + split[1]).eq("type", 3));
                    if (oldAreaSpace != null) {
                        log.info("找到已存在的区县节点: {}", oldAreaSpace.getGuid());
                        area = oldAreaSpace;
                        area.setId(null);
                    }

                    area.setType(3);
                    area.setUpdateTime(new Date());
                    area.setGuid(areaGuid);
                    area.setName(split[1]);
                    area.setParentGuid(citySpace.getGuid());
                    area.setSpaceType("区县");
                    area.setDelFlag(0);

                    boolean areaSaveResult = focSpaceService.saveOrUpdate(area);
                    log.info("区县节点保存/更新结果: {}, guid: {}", areaSaveResult, area.getGuid());

                    //将老节点对应的局方挂载到新节点下面
                    log.info("开始更新房间节点的父级关系，从 {} 到 {}", focSpace.getGuid(), area.getGuid());
                    spaceLambdaUpdateWrapper = new LambdaUpdateWrapper<FocSpace>();
                    spaceLambdaUpdateWrapper.eq(FocSpace::getSpaceType, "房间");
                    spaceLambdaUpdateWrapper.eq(FocSpace::getParentGuid, focSpace.getGuid());
                    spaceLambdaUpdateWrapper.set(FocSpace::getParentGuid, area.getGuid());
                    boolean roomUpdateResult = focSpaceService.update(spaceLambdaUpdateWrapper);
                    log.info("房间节点父级关系更新结果: {}", roomUpdateResult);

                    //更新源节点为删除
                    focSpace.setDelFlag(1);
                    boolean deleteResult = focSpaceService.updateById(focSpace);
                    log.info("源楼宇节点删除标记设置结果: {}", deleteResult);

                    processedCount++;
                    log.info("楼宇 {} 处理完成", focSpace.getName());

                } catch (Exception e) {
                    errorCount++;
                    log.error("处理楼宇数据时发生异常: guid={}, name={}, error={}",
                            focSpace.getGuid(), focSpace.getName(), e.getMessage(), e);
                }
            }

            log.info("spaceConvertSide方法执行完成 - 成功处理: {}, 错误: {}, 总计: {}",
                    processedCount, errorCount, list.size());

        } catch (Exception e) {
            log.error("spaceConvertSide方法执行过程中发生异常: {}", e.getMessage(), e);
            throw new RuntimeException("处理省份和城市区县转换时发生异常", e);
        }

        return FocRespone.ok();
    }

    /**
     * 处理局站转换
     */
    @AutoLog(value = "foc操作-手动刷新-下划线")
    @ApiOperation(value = "foc操作-手动刷新-下划线", notes = "foc操作-手动刷新-下划线")
    @RequestMapping(value = "/spaceConvert")
    @Transactional(rollbackFor = Exception.class)
    public FocRespone spaceConvert() {
        log.info("开始执行spaceConvert方法 - 处理局站转换");

        try {
            //先获取所有的区县
            log.info("开始查询所有区县数据");
            LambdaQueryWrapper<FocSpace> focSpaceLambdaQueryWrapper = new QueryWrapper<FocSpace>().lambda();
            focSpaceLambdaQueryWrapper.eq(FocSpace::getType, 3);
            List<FocSpace> specList = focSpaceService.list(focSpaceLambdaQueryWrapper);
            log.info("查询到区县数据数量: {}", specList != null ? specList.size() : 0);

            if (CollectionUtil.isEmpty(specList)) {
                log.warn("区县数据为空，直接返回");
                return FocRespone.ok();
            }

            //遍历所有的区县
            int processedAreaCount = 0;
            int processedSideCount = 0;
            int errorCount = 0;

            for (FocSpace focSpace : specList) {
                try {
                    log.info("开始处理区县: guid={}, name={}", focSpace.getGuid(), focSpace.getName());

                    //根据区县获取所有的局房站点
                    focSpaceLambdaQueryWrapper = new QueryWrapper<FocSpace>().lambda();
                    focSpaceLambdaQueryWrapper.eq(FocSpace::getParentGuid, focSpace.getGuid());
                    focSpaceLambdaQueryWrapper.eq(FocSpace::getSpaceType, "房间");
                    focSpaceLambdaQueryWrapper.eq(FocSpace::getDelFlag, 0);
                    List<FocSpace> sideList = focSpaceService.list(focSpaceLambdaQueryWrapper);

                    log.info("区县 {} 下查询到房间数据数量: {}", focSpace.getName(), sideList != null ? sideList.size() : 0);

                    //如果为空跳过
                    if (CollectionUtil.isEmpty(sideList)) {
                        log.info("区县 {} 下没有房间数据，跳过处理", focSpace.getName());
                        continue;
                    }

                    for (FocSpace sideSpec : sideList) {
                        try {
                            log.info("开始处理房间: guid={}, name={}", sideSpec.getGuid(), sideSpec.getName());

                            //局站名称中存在下划线，则进行划分
                            if (sideSpec.getName().contains("_")) {
                                log.info("房间名称包含下划线，开始分割处理: {}", sideSpec.getName());

                                //将局站进分割为局房和站点
                                String[] split = sideSpec.getName().split("_");
                                if (split == null) {
                                    log.warn("房间名称分割结果为空: {}", sideSpec.getName());
                                    errorCount++;
                                    continue;
                                }
                                if (split.length != 2) {
                                    log.warn("房间名称分割长度不正确，期望2个部分，实际{}个部分: {}", split.length, sideSpec.getName());
                                    errorCount++;
                                    continue;
                                }
                                if (split[1] == null) {
                                    log.warn("房间名称分割后第二部分为空: {}", sideSpec.getName());
                                    errorCount++;
                                    continue;
                                }

                                log.info("房间名称分割成功: 局房={}, 站点={}", split[0], split[1]);

                                // 创建局房节点
                                FocSpace side = new FocSpace();
                                //查询是否存在老局房
                                String sideGuid = focSpace.getParentGuid() + "_" + focSpace.getName() + "_" + split[0];
                                log.info("查询局房节点，guid: {}", sideGuid);
                                FocSpace oldSide = focSpaceService.getOne(new QueryWrapper<FocSpace>().eq("guid", sideGuid).eq("type", 4));
                                if (oldSide != null) {
                                    log.info("找到已存在的局房节点: {}", oldSide.getGuid());
                                    side = oldSide;
                                    side.setId(null);
                                }

                                //生成新的局房guid 和名称
                                side.setGuid(sideGuid);
                                side.setUpdateTime(new Date());
                                side.setName(split[0]);
                                side.setType(4);
                                side.setParentGuid(focSpace.getGuid());

                                side.setDelFlag(0);

                                boolean sideSaveResult = focSpaceService.saveOrUpdate(side);
                                log.info("局房节点保存/更新结果: {}, guid: {}", sideSaveResult, side.getGuid());

                                //继续生成新的机房站点
                                FocSpace romSpec = new FocSpace();
                                //查询是否存在老机房
                                String romGuid = focSpace.getParentGuid() + "_" + focSpace.getName() + "_" + split[0] + "_" + split[1];
                                log.info("查询机房节点，guid: {}", romGuid);
                                FocSpace oldRomSpec = focSpaceService.getOne(new QueryWrapper<FocSpace>().
                                        eq("guid", romGuid).eq("type", 5).eq("name", split[1]));
                                if (oldRomSpec != null) {
                                    log.info("找到已存在的机房节点: {}", oldRomSpec.getGuid());
                                    //如果存在，则将老机房的映射属性，映射到新机房下
                                    romSpec = oldRomSpec;
                                    romSpec.setId(null);
                                }

                                romSpec.setGuid(sideSpec.getGuid() + "N");
                                romSpec.setUpdateTime(new Date());
                                romSpec.setName(split[1]);
                                romSpec.setDelFlag(0);
                                romSpec.setType(5);
                                romSpec.setParentGuid(side.getGuid());

                                boolean romSaveResult = focSpaceService.saveOrUpdate(romSpec);
                                log.info("机房节点保存/更新结果: {}, guid: {}", romSaveResult, romSpec.getGuid());

                                //将所有设备挂载到新的机房站点下
                                log.info("开始更新设备节点的父级关系，从 {} 到 {}", sideSpec.getGuid(), romSpec.getGuid());
                                LambdaUpdateWrapper<FocDevice> focDeviceLambdaUpdateWrapper = new LambdaUpdateWrapper<FocDevice>();
                                focDeviceLambdaUpdateWrapper.eq(FocDevice::getParentGuid, sideSpec.getGuid());
                                focDeviceLambdaUpdateWrapper.set(FocDevice::getParentGuid, romSpec.getGuid());
                                boolean deviceUpdateResult = focDeviceService.update(focDeviceLambdaUpdateWrapper);
                                log.info("设备节点父级关系更新结果: {}", deviceUpdateResult);

                                //更新原节点为删除
                                sideSpec.setDelFlag(1);
                                boolean deleteResult = focSpaceService.updateById(sideSpec);
                                log.info("源房间节点删除标记设置结果: {}", deleteResult);

                                processedSideCount++;
                                log.info("房间 {} 处理完成", sideSpec.getName());

                            } else {
                                log.info("房间名称不包含下划线，跳过处理: {}", sideSpec.getName());
                            }

                        } catch (Exception e) {
                            errorCount++;
                            log.error("处理房间数据时发生异常: guid={}, name={}, error={}",
                                    sideSpec.getGuid(), sideSpec.getName(), e.getMessage(), e);
                        }
                    }

                    processedAreaCount++;
                    log.info("区县 {} 处理完成", focSpace.getName());

                } catch (Exception e) {
                    errorCount++;
                    log.error("处理区县数据时发生异常: guid={}, name={}, error={}",
                            focSpace.getGuid(), focSpace.getName(), e.getMessage(), e);
                }
            }

            log.info("spaceConvert方法执行完成 - 成功处理区县: {}, 成功处理房间: {}, 错误: {}, 总计区县: {}",
                    processedAreaCount, processedSideCount, errorCount, specList.size());

        } catch (Exception e) {
            log.error("spaceConvert方法执行过程中发生异常: {}", e.getMessage(), e);
            throw new RuntimeException("处理局站转换时发生异常", e);
        }

        log.info("局房刷新完成");
        return FocRespone.ok();
    }

    /**
     * 登出
     */
    @AutoLog(value = "foc操作-登出")
    @ApiOperation(value = "foc操作-登出", notes = "foc操作-登出")
    @RequestMapping(value = "/logout")
    public FocRespone logout() {
        FocRequest focRequest = new FocRequest();
        focRequest.setData(null);
        log.debug("登出请求路径以及参数：" + emsUrl + "/north/logout" + " 请求参数：" + JSONObject.toJSONString(focRequest, SerializerFeature.WriteMapNullValue) + "[token]" + redisUtil.get("token"));
        HttpResponse execute = HttpUtil.createPost(emsUrl + "/north/logout").header("token", redisUtil.get("token").toString()).body(JSONObject.toJSONString(focRequest)).execute();
        String body = execute.body();
        log.debug("登出返回信息：{}", body);
        return FocRespone.ok();
    }

    /**
     * 登录foc
     */
    @AutoLog(value = "foc操作-手动获取配置")
    @ApiOperation(value = "foc操作-手动获取配置", notes = "foc操作-手动获取配置")
    @RequestMapping(value = "/getConfig")
    @Transactional(rollbackFor = Exception.class)
    public FocRespone getConfig() {
        // todo 检测登录状态。登录状态失效重新登录
        //默认对所有节点进行删除
        UpdateWrapper<FocSpace> focSpaceUpdateWrapper = new UpdateWrapper<>();
        focSpaceUpdateWrapper.set("del_flag", 1);
        focSpaceService.update(focSpaceUpdateWrapper);
        FocRequest focRequest = new FocRequest();
        FocConfig byId = focConfigService.getById(1);
        log.debug("获取配置对象:" + JSONObject.toJSONString(byId));
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("version", StringUtils.isEmpty(byId.getVersion()) ? null : byId.getVersion());
        jsonObject.put("page_no", "1");
        jsonObject.put("page_size", "999");
        focRequest.setData(jsonObject);
        log.debug("获取配置请求路径以及参数：" + emsUrl + "/north/config_get" + " 请求参数：" + JSONObject.toJSONString(focRequest, SerializerFeature.WriteMapNullValue) + "[token]" + redisUtil.get("token"));
        HttpResponse execute = HttpUtil.createPost(emsUrl + "/north/config_get").header("token", redisUtil.get("token").toString()).body(JSONObject.toJSONString(focRequest, SerializerFeature.WriteMapNullValue)).execute();
        String post = execute.body();
        log.info("获取配置返回信息：{}", post);
        JSONObject result = JSONObject.parseObject(post);
        result = result.getJSONObject("data");
        String emsVer = result.getString("version");
        String page_no = result.getString("page_no");
        String page_size = result.getString("page_size");
        String size = result.getString("size");
        String total = result.getString("total");
        JSONArray nodes = result.getJSONArray("nodes");
        if (!emsVer.equals(byId.getVersion())) {
            //计算还需要请求几次
            int count = Integer.parseInt(total) / Integer.parseInt(page_size);
            if (Integer.parseInt(total) % Integer.parseInt(page_size) != 0) {
                count++;
            }
            //保存配置
            saveConfig(nodes);
            for (int i = 2; i < count + 1; i++) {
                jsonObject.put("page_no", i + "");
                jsonObject.put("version", emsVer);
                focRequest.setData(jsonObject);
                log.debug("获取配置请求路径以及参数：" + emsUrl + "/north/config_get" + " 请求参数：" + JSONObject.toJSONString(focRequest, SerializerFeature.WriteMapNullValue) + "[token]" + redisUtil.get("token"));
                execute = HttpUtil.createPost(emsUrl + "/north/config_get").header("token", redisUtil.get("token").toString()).body(JSONObject.toJSONString(focRequest, SerializerFeature.WriteMapNullValue)).execute();
                post = execute.body();
                log.info("获取配置返回信息：{}", post);
                result = JSONObject.parseObject(post);
                result = result.getJSONObject("data");
                nodes = result.getJSONArray("nodes");
                saveConfig(nodes);
            }

            //版本有更新，重新生成局房结构
            //省市区转换
            // spaceConvertSide();
            //局站转换
            //spaceConvert();
        }
        //修改版本
        byId.setVersion(emsVer);
        focConfigService.updateById(byId);
        try {
            spaceConvertAll();
        } catch (Exception e) {
            log.info("局房转换异常", e);
        }
        return FocRespone.ok();
    }


    @Transactional(rollbackFor = Exception.class)
    public void jobConfig() {
        //默认对所有节点进行删除
        UpdateWrapper<FocSpace> focConfigUpdateWrapper = new UpdateWrapper<>();
        focConfigUpdateWrapper.set("del_flag", 1);
        focSpaceService.update(focConfigUpdateWrapper);
        FocRequest focRequest = new FocRequest();
        FocConfig byId = focConfigService.getById(1);
        log.debug("获取配置对象:" + JSONObject.toJSONString(byId));
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("version", StringUtils.isEmpty(byId.getVersion()) ? null : byId.getVersion());
        jsonObject.put("page_no", "1");
        jsonObject.put("page_size", "999");
        focRequest.setData(jsonObject);
        log.debug("获取配置请求路径以及参数：" + emsUrl + "/north/config_get" + " 请求参数：" + JSONObject.toJSONString(focRequest, SerializerFeature.WriteMapNullValue) + "[token]" + redisUtil.get("token"));
        HttpResponse execute = HttpUtil.createPost(emsUrl + "/north/config_get").header("token", redisUtil.get("token").toString()).body(JSONObject.toJSONString(focRequest, SerializerFeature.WriteMapNullValue)).execute();
        String post = execute.body();
        log.debug("获取配置返回信息：{}", post);
        JSONObject result = JSONObject.parseObject(post);
        result = result.getJSONObject("data");
        String emsVer = result.getString("version");
        String page_no = result.getString("page_no");
        String page_size = result.getString("page_size");
        String size = result.getString("size");
        String total = result.getString("total");
        JSONArray nodes = result.getJSONArray("nodes");
        if (!emsVer.equals(byId.getVersion())) {
            //计算还需要请求几次
            int count = Integer.parseInt(total) / Integer.parseInt(page_size);
            if (Integer.parseInt(total) % Integer.parseInt(page_size) != 0) {
                count++;
            }
            //保存配置
            saveConfig(nodes);
            for (int i = 2; i < count + 1; i++) {
                jsonObject.put("page_no", i + "");
                jsonObject.put("version", emsVer);
                focRequest.setData(jsonObject);
                log.debug("获取配置请求路径以及参数：" + emsUrl + "/north/config_get" + " 请求参数：" + JSONObject.toJSONString(focRequest, SerializerFeature.WriteMapNullValue) + "[token]" + redisUtil.get("token"));
                execute = HttpUtil.createPost(emsUrl + "/north/config_get").header("token", redisUtil.get("token").toString()).body(JSONObject.toJSONString(focRequest, SerializerFeature.WriteMapNullValue)).execute();
                post = execute.body();
                log.debug("获取配置返回信息：{}", post);
                result = JSONObject.parseObject(post);
                result = result.getJSONObject("data");
                nodes = result.getJSONArray("nodes");
                saveConfig(nodes);
            }
        }
        //修改版本
        byId.setVersion(emsVer);
        focConfigService.updateById(byId);
        try {
            spaceConvertAll();
            //转换完成后，对已删除的节点进行删除
            cleanupDeletedNodes();
        } catch (Exception e) {
            log.info("局房转换异常", e);
        }
    }

    /**
     * 清理已删除的节点及相关数据
     */
    private void cleanupDeletedNodes() {
        //对已经删除的节点进行删除
        List<FocSpace> focSpaceList = focSpaceService.list(new QueryWrapper<FocSpace>().eq("del_flag", 1));
        for (FocSpace focSpace : focSpaceList) {
            //先删除节点
            focSpaceService.remove(new QueryWrapper<FocSpace>().eq("guid", focSpace.getGuid()));
            if (focSpace.getType() != null) {
                if (focSpace.getType() == 1 || focSpace.getType() == 2 || focSpace.getType() == 3) {
                    //判断是否还存在区域id
                    if (StringUtils.isNotEmpty(focSpace.getAreaid())) {
                        Long count = focSpaceService.count(new QueryWrapper<FocSpace>().eq("areaid", focSpace.getAreaid()));
                        if (count == 0) {
                            mAreaService.remove(new QueryWrapper<MArea>().eq("areaid", focSpace.getAreaid()));
                        }
                    } else if (focSpace.getType() == 4) {
                        //判断是否还存在局房id
                        if (StringUtils.isNotEmpty(focSpace.getSiteid())) {
                            Long count = focSpaceService.count(new QueryWrapper<FocSpace>().eq("siteid", focSpace.getSiteid()));
                            if (count == 0) {
                                mSiteService.remove(new QueryWrapper<MSite>().eq("siteid", focSpace.getSiteid()));
                            }
                        } else if (focSpace.getType() == 5) {
                            //判断是否还存在机房id
                            if (StringUtils.isNotEmpty(focSpace.getRoomid())) {
                                Long count = focSpaceService.count(new QueryWrapper<FocSpace>().eq("roomid", focSpace.getRoomid()));
                                if (count == 0) {
                                    mRoomService.remove(new QueryWrapper<MRoom>().eq("roomid", focSpace.getRoomid()));
                                }
                            }
                        }
                    }

                    //对已经删除的设备编码进行清楚处理，并且该id在focDevice表中不存在
                    List<FocDevice> focDeviceList = focDeviceService.list(new QueryWrapper<FocDevice>().eq("del_flag", 1));
                    for (FocDevice focDevice : focDeviceList) {
                        focDeviceService.remove(new QueryWrapper<FocDevice>().eq("guid", focDevice.getGuid()));
                        if (StringUtils.isNotEmpty(focDevice.getDeviceid())) {
                            //判断设备id在mDevice表中不存在
                            Long count = focDeviceService.count(new QueryWrapper<FocDevice>().eq("deviceid", focDevice.getDeviceid()));
                            if (count == 0) {
                                mDeviceService.remove(new QueryWrapper<MDevice>().eq("devassestid", focDevice.getDeviceid()));
                            }
                        }
                    }

                    //对已映射的信号进行删除，删除条件为guid在foc_point表中存在
                    List<FocPoint> focPointList = focPointService.list(new QueryWrapper<FocPoint>().eq("del_flag", 1));
                    for (FocPoint focPoint : focPointList) {
                        mSignalService.remove(new QueryWrapper<MSignal>().eq("guid", focPoint.getGuid()));
                    }
                    focPointService.remove(new QueryWrapper<FocPoint>().eq("del_flag", 1));
                    //转换完成后，删除未映射的设备、机房、局房、区县、
                }
            }
        }
    }


    void saveConfig(JSONArray nodes) {
        if (CollectionUtil.isEmpty(nodes)) {
            return;
        }
        for (int j = 0; j < nodes.size(); j++) {
            JSONObject jsonObject1 = nodes.getJSONObject(j);
            Integer nodetype = jsonObject1.getInteger("node_type");
            if (nodetype == 1) {
                //将Json转为空间对象,空间对象默认不会改变
                FocSpace focSpace = jsonObject1.toJavaObject(FocSpace.class);
                focSpace.setDelFlag(0);
                focSpaceService.saveOrUpdate(focSpace);
            } else if (nodetype == 2) {
                //将Json转为设备对象
                FocDevice focDevice = jsonObject1.toJavaObject(FocDevice.class);
                //如果是设备对象，处理设备名称
                try {
                    focDevice.setName(focDevice.getName().split("\\^")[0]);
                } catch (Exception e) {
                    log.info("设备名称处理异常：{}", e.getMessage() + "设备名称：" + focDevice.getName());
                }
                focDevice.setDelFlag(0);
                focDeviceService.saveOrUpdate(focDevice);
            } else if (nodetype == 3) {
                //转为点位对象
                FocPoint focPoint = jsonObject1.toJavaObject(FocPoint.class);
                focPoint.setDelFlag(0);
                if ("5".equals(focPoint.getPointType())) {
                    //告警节点
                    if (StringUtils.isNotEmpty(focPoint.getStatusMap())) {
                        //使用分号进行分割
                        String[] statusMap = focPoint.getStatusMap().split(";");
                        for (int i = 0; i < statusMap.length; i++) {
                            FocPoint focPointNew = new FocPoint();
                            BeanUtils.copyProperties(focPoint, focPointNew);
                            String[] alarmArray = statusMap[i].split("=");
                            //重新设置guid
                            focPointNew.setGuid(focPoint.getGuid() + "_" + alarmArray[0]);
                            focPointNew.setName(focPoint.getName() + "_" + alarmArray[1]);
                            focPointNew.setStatusMap(statusMap[i]);
                            focPointNew.setDelFlag(0);
                            focPointService.saveOrUpdate(focPointNew);
                        }

                    }
                    //原告警点位隐藏
                    focPoint.setDelFlag(1);
                    focPointService.saveOrUpdate(focPoint);

                } else {
                    focPoint.setDelFlag(0);
                    focPointService.saveOrUpdate(focPoint);
                }

            }

        }

    }


    public static void main(String[] args) {

        String str = "971000545.971020006.43203032.0.0000000011";
        String st1 = str.length() > 10 ? str.substring(str.length() - 10) : str;

        System.out.println(st1);
    }


}
